package com.java.forum.d_controller;


import com.java.forum.e_util.JsonResult;
import com.java.forum.g_exception.Exceptions;
import com.java.forum.g_exception.ServiceException;
import com.java.forum.h_annotation.NeedToken;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("file")
public class FileController extends BaseController {

    @Value("${file-save-path}")
    private String fileSavePath;

    @NeedToken
    @RequestMapping("upload")
    public JsonResult<Map<String, String>> upload(MultipartFile file, HttpServletRequest request) throws IOException {
        if (file.isEmpty()) throw new ServiceException(Exceptions.FileEmptyException);
        UUID uuid = UUID.randomUUID();
        String filename = System.currentTimeMillis() + uuid.toString().replaceAll("-", "").substring(0, 6);
        File localFile = new File(fileSavePath + filename);
        file.transferTo(localFile);
        Map<String, String> map = new HashMap<>();
        String url = request.getScheme() + "://" + request.getServerName() + ":" +
                request.getServerPort() + "/images/" + filename;
        map.put("url", url);
        return new JsonResult<>(ok, map);
    }
}
